package com.httpServerMock.HttpServerMock.controller;

import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

@RestController
public class MockController {
	@Autowired
	RestTemplate restTemplate;
	
	@Value("${spring.application.name}")
	private String appName;
	
	@Value("${moco.address}")
	private String mocoAddress;
	
	/*
	 * 两级或多级可能需要两个*
	 */
	@RequestMapping(value = "/**", method = RequestMethod.GET)
	public Object getAll(HttpServletRequest httpServletRequest ,@RequestParam Map<String, Object> requestMap) {
		StringBuffer mocoUrl = new StringBuffer();
		mocoUrl.append("http://").append(mocoAddress).append("/")
		.append(appName).append("/").append(httpServletRequest.getServletPath());
		if(!requestMap.isEmpty()){
			mocoUrl.append("?");
			boolean first = true;
			for(String key:requestMap.keySet()){
				if(!first){
					mocoUrl.append("&");
				}
				first = false;
				mocoUrl.append(key).append("={").append(key).append("}");
			}
		}
		String jsonStr = restTemplate.getForEntity(mocoUrl.toString(), String.class,requestMap).getBody();
		Object object = JSONObject.parse(jsonStr);
		return object;
	}
	
	@RequestMapping(value = "/**", method = RequestMethod.POST)
	public Object postAll(HttpServletRequest httpServletRequest ,@RequestBody Object requestBody) {
		String requestJsonStr = JSON.toJSONString(requestBody);
		StringBuffer mocoUrl = new StringBuffer();
		mocoUrl.append("http://").append(mocoAddress).append("/")
		.append(appName).append("/").append(httpServletRequest.getServletPath());
		String jsonStr = restTemplate.postForEntity(mocoUrl.toString(), requestJsonStr,String.class).getBody();
		Object object = JSONObject.parse(jsonStr);
		return object;
	}
}